package com.itheima.dao;

import com.itheima.domain.Student;

import java.util.ArrayList;

/*
使用集合 替换数组
 */
public class OtherStudentDao implements BaseStudentDao{
    //获取数组
    private static ArrayList<Student> stus= new ArrayList<>();
    static {
        Student wu = new Student("0001", "吴亦凡", 31, "1991-01-01");
        Student lu = new Student("0002", "鹿晗", 31, "1991-01-01");
        Student huang = new Student("0003", "黄子韬", 31, "1991-01-01");
        Student zhang = new Student("0004", "张艺兴", 31, "1991-01-01");
        stus.add(wu);
        stus.add(lu);
        stus.add(huang);
        stus.add(zhang);
    }


    public boolean addStudent(Student student) {
        stus.add(student);
        return true;

    }
    //查询所有学生的方法
    public Student[] findAllStudent() {
        //将集合转换成数组
        //创建 数组
        //遍历集合将集合中的元素依次放入数组中
        Student[] students = new Student[stus.size()];
        for (int i = 0; i < stus.size(); i++) {
            //stus i students i
            students[i]= stus.get(i);
        }
        return students;
    }

    //删除方法
    //参数  String sid
    //返回值   没有
    public void  deleteStudent(String sid){
        //找到sid 所在的位置
        int index = getIndex(sid);
        //找到直接赋值为null
        stus.remove(index);

    }
    //根据学号找索引  查
    //参数 String sid
    //返回值 int
    public int getIndex(String sid){
        //遍历数组
        for (int i = 0; i < stus.size(); i++) {
            //获取每一个学生
            //判断学生的sid 和参数sid 是否一致
            Student stu = stus.get(i);
            if(stu!=null&&stu.getSid().equals(sid)){
                //一致 返回索引
                return i;
            }
            //不一致 下一次
        }
        //所有的都找不到
        return -1;

    }

    public void updateStudent(String sid, Student student) {
        //根据学号找索引
        int index = getIndex(sid);
        //替换
       stus.set(index,student);
    }
}
